var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
const stringRandom = require('string-random');
var renshu = 0;

// 使用express托管静态资源
app.use(require('express').static('public'));

// 对于处理首页的路由
app.get('/', function (req, res) {
  // 重定向到index.html
  res.redirect('lempChat.html');
});

global.allData = [];
setInterval(() => {
  if (global.allData.length <= 0) return;

  let _time = 1000 * 60 * 60 * 24;
  // let _time = 1000 * 60 * 60 * 12;
  // let _time = 1000 * 60 * 60 * 2;
  // let _time = 1000 * 60;
  let len = -1;
  for (let index = 0; index < global.allData.length; index++) {
    const element = global.allData[index];
    if ((element.time + _time) > new Date().getTime()) {
      break;
    } else {
      len++;
    }
  }
  if (len != -1) { global.allData.splice(0, len + 1) }

}, 1000 * 60 * 10);

io.on('connection', function (socket) {
  // 用户连接
  renshu++;
  io.emit('renshu', renshu);

  // 用户第一次链接，发送旧数据
  socket.emit('init', global.allData);

  socket.on('disconnect', function () {
    // 用户断开
    renshu--;
    io.emit('renshu', renshu);
  });

  // 进行消息广播
  socket.on('sendMessage', (data) => {
    // console.log(data);
    io.emit('sendMessage', data);
    global.allData.push(data)
    // console.log(``, data)
  });

  // 进行图片消息广播
  socket.on('sendimage', (data) => {
    // console.log(data.img);
    io.emit('sendimage', data);
    global.allData.push(data)
  });
});

// 服务器监听端口,可修改
http.listen(3000, function () {
  console.log("运行成功，正在监听3000端口");
});
